package com.example.gateway.controller;

import com.example.gateway.request.UriReq;
import com.github.kevinsawicki.http.HttpRequest;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class GatewayCotroller {
    @Resource
    RedisTemplate redisTemplate;

    @RequestMapping("{serviceName}/{api}")
    public String gateway(@PathVariable String serviceName, @PathVariable String api) {
        List<UriReq> redisLpush = redisTemplate.opsForList().range("redisLpush", 0, -1);
        System.out.println(redisLpush.get(0).getName() + ">>>>>>>");
        List<UriReq> collect = redisLpush.stream().filter(info -> info.getName().equals(serviceName)).collect(Collectors.toList());

        if (!collect.isEmpty()) {
            UriReq uriReq = collect.stream().findFirst().get();
            String url = "http://" + uriReq.getIp() + ":" + uriReq.getPort() + "/" + api;
            String httpRequest = HttpRequest.get(url).body();
            return httpRequest;
        } else {
            return serviceName + " 服务尚未注册，请注册后重试";
        }
    }




    @GetMapping("/gateway/{serverAName}/{interfaceName}")
    public String myGateway(@PathVariable("serverAName") String servername, @PathVariable("interfaceName") String interfacename){
//        redis 服务注册中心寻找服务，返回服务地址
        String url = (String)redisTemplate.opsForValue().get(servername);
        if (url == null || url.equals("")) return "无相应服务，请注册后重试";
//          服务中心找到该服务，用户访问服务地址
        String target = url +"/"+interfacename;
        System.out.println(target);
        RestTemplate restTemplate = new RestTemplateBuilder().build();
        String response="";
        try {
             response = restTemplate.getForObject(target, String.class);
        }catch (Exception e){
            return "简易网关访问:访问失败";
        }


        return "简易网关访问:" + response;
    }
}
